package com.doubao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubao.config.MinioConfig;
import com.doubao.entity.SmartDevice;
import com.doubao.entity.dto.UserLoginDTO;
import com.doubao.entity.vo.UserVO;
import com.doubao.exception.BusinessException;
import com.doubao.mapper.UserMapper;
import com.doubao.entity.User;
import com.doubao.response.WxLoginResponse;
import com.doubao.service.UserService;
import com.doubao.service.SmartDeviceService;
import com.doubao.service.WxService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final WxService wxService;
    private final SmartDeviceService smartDeviceService;
    private final RedisTemplate<String, Object> redisTemplate;
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    private final MinioConfig minioConfig; // 添加 MinioConfig 字段

   @Override
@Transactional(rollbackFor = Exception.class)
public UserVO wxLogin(UserLoginDTO dto) {
    // 1.通过code获取微信会话信息
    WxLoginResponse wxResponse = wxService.getWxSession(dto.getCode());

    // 2. 查询是否存在该用户
    User user = this.lambdaQuery()
            .eq(User::getOpenId, wxResponse.getOpenid())
            .one();

    if (user == null) {
        // 3. 新用户注册
        user = new User();
        user.setOpenId(wxResponse.getOpenid());
        // 设置用户昵称,如果没传使用默认值
        user.setUsername(StringUtils.defaultIfBlank(dto.getUsername(), "微信用户" + wxResponse.getOpenid().substring(0, 5)));
        // 设置用户头像,如果没传使用默认值
        user.setAvatar(StringUtils.defaultIfBlank(dto.getAvatar(), "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0"));
        user.setDoubaoId(generateDoubaoId());
        user.setStatus(1);
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());

        boolean saved = this.save(user);
        log.info("新用户注册{}, 用户ID：{}", saved ? "成功" : "失败", user.getId());

        // 初始化系统默认AI助手
        if (saved) {
            initDefaultSmartDevices(user.getId());
        }
    } else {
        // 4. 更新用户信息
        boolean needUpdate = false;

        // 如果传入了新的昵称和头像,就更新
        if (StringUtils.isNotBlank(dto.getUsername()) && !dto.getUsername().equals(user.getUsername())) {
            user.setUsername(dto.getUsername());
            needUpdate = true;
        }
        if (StringUtils.isNotBlank(dto.getAvatar()) && !dto.getAvatar().equals(user.getAvatar())) {
            user.setAvatar(dto.getAvatar());
            needUpdate = true;
        }

        if (needUpdate) {
            user.setUpdatedAt(LocalDateTime.now());
            boolean updated = this.updateById(user);
            log.info("用户信息更新{}, 用户ID：{}", updated ? "成功" : "失败", user.getId());
        }
    }

    // 5. 生成token并存储到Redis
    String token = generateToken();
    String tokenKey = "user:token:" + token;
    redisTemplate.opsForValue().set(tokenKey, user.getId(), 7, TimeUnit.DAYS);

    // 6. 构造返回对象
    UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
    userVO.setToken(token);
    return userVO;
}

    /**
     * 生成token
     */
    private String generateToken() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserVO phoneLogin(String phone, String code) {
        // 验证验证码
        String cacheCode = (String) redisTemplate.opsForValue().get("login:code:" + phone);
        if (!code.equals(cacheCode)) {
            throw new BusinessException("验证码错误");
        }

        User user = this.lambdaQuery()
                .eq(User::getPhone, phone)
                .one();

        if (user == null) {
            // 新用户注册
            user = new User();
            user.setPhone(phone);
            user.setUsername("用户" + phone.substring(7));
            user.setDoubaoId(generateDoubaoId());
            user.setStatus(1);
            this.save(user);

            // 初始化系统预设AI助手
            initDefaultSmartDevices(user.getId());
        }

        return BeanUtil.copyProperties(user, UserVO.class);
    }

    @Override
    public void updateUserInfo(Long userId, UserVO userVO) {
        User user = getById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 更新用户信息
        user.setUsername(userVO.getUsername());
        user.setAvatar(userVO.getAvatar());
        user.setPrivacySetting(userVO.getPrivacySetting());
        updateById(user);
    }

    @Override
    public UserVO getUserInfo(Long userId) {
        User user = getById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        return BeanUtil.copyProperties(user, UserVO.class);
    }

    /**
     * 生成豆包号
     */
    private String generateDoubaoId() {
        String id;
        do {
            // 生成8位随机字符串
            id = RandomUtil.randomString(8);
        } while(this.lambdaQuery().eq(User::getDoubaoId, id).exists());
        return id;
    }

    /**
     * 初始化系统预设AI助手
     */
    private void initDefaultSmartDevices(Long userId) {
        // 直接构建默认头像URL
        String avatarUrl = String.format("%s/%s/avatar.jpg",
                minioConfig.getEndpoint(),
                minioConfig.getBucketName()
        );

        // 创建默认助手
        SmartDevice assistant = new SmartDevice();
        assistant.setUserId(userId);
        assistant.setName("小糯米助手");
        assistant.setDescription("你好！我是你的智能助手小糯米，让我们开始愉快的对话吧！");
        assistant.setSystemPrompt("你是一个友善的AI助手，名叫小糯米。你会用简单易懂的语言回答问题。");
        assistant.setVisibility(0);  // 私密
        assistant.setType(1);        // 系统预设
        assistant.setCategory("助手");
        assistant.setIcon(avatarUrl); // 使用构建的URL

        smartDeviceService.save(assistant);

        // 更新用户智能体数量
        this.lambdaUpdate()
                .set(User::getSmartDeviceCount, 1)
                .eq(User::getId, userId)
                .update();
    }

}